﻿function GroupViewHandler(options) {
	var _this = this;
	this.count = -1;
	this.grid = null;
	this.selectGroup = function(groupNode, groupRow) {
		for (var i=0;i<groupNode.children.length;i++) $(groupNode.children[i].row).addClass('ui-state-focus');
	};
	
	this.toggleGroup = function(groupNode, groupRow) {
		for (var i=0;i<groupNode.children.length;i++) $(groupNode.children[i].row).toggle();
		_this.grid.pageChanged.trigger();
	};
	
	this.refresh = function() {
		if (loader._oldcallparams != null) {
			this.get(loader._oldcallparams.from, loader._oldcallparams.to, loader._oldcallparams.callback);
		}
	};
	
	this.get = function(from, to, callback) {
		_this.grid.dataLoader.get(from, to, function(data) {
			_this.count = data.total;
			var groups = new Map();
			for (var i=0;i< data.items.length;i++) {
				var a = groups.get(data.items[i][options.field]);
				if (a == null) {
					a = [];
					groups.put(data.items[i][options.field], a);
				}
				a.push(new Node(data.items[i]));
			}
			var tree = new Node({root: 'root'});
			
			$(groups.getKeys()).each(function(e, key) {
				var groupNode = new Node({id: key});
				
				groupNode.setChildren(groups.get(key));
				groupNode.renderer = function(table, columns) {
					var tr = $('<tr>');
					return tr.addClass('dt-table-group-header')
						.append(
							$('<td>').attr('colspan', columns.length)
							.css('vertical-align', 'center')
							.append(
								$('<button>').
									html(key + ' ['+groupNode.children.length+' items]').
									button({icons: {primary: "ui-icon-plus"}}).
									click(function() {
										$(this).find('.ui-button-icon-primary').toggleClass('ui-icon-minus ui-icon-plus');
										_this.toggleGroup(groupNode, tr);
									}).css('border', 0).css('background','none')
							)
					);
				};
				
				tree.addChild(groupNode);
			});
			
			callback(data, tree);
		});
	}
	
	this.attachListener = function() {
		_this.grid.refresh();
	};
	
	this.attach = function(grid) {
		this.grid = grid;
		this.grid.loader = this;
		this.grid.attached.add(this.attachListener);
		
		if (this.grid.isAttached) {
			this.grid.refresh();
		}
	};
	
	this.detach = function() {
		this.grid.attached.remove(this.attachListener);
		this.grid.loader = null;
	};
}; GroupViewHandler.inherits(DatagridPlugin);